package game.module.battlereport.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import db.proto.ProtoMessageQzmj;
import db.proto.ProtoMessageQzmj.AllRound;
import game.common.DaoCommonHandler;
import game.db.DataSourceManager;
import game.module.battlereport.bean.BattleReport;
import lion.common.MyBlob;

public class BattleReportDBDao {

	private static Logger logger = LoggerFactory.getLogger(BattleReportDBDao.class);

	private DataSource dataSource = DataSourceManager.getInstance().getDataSource();

	static class SingletonHolder {
		static BattleReportDBDao instance = new BattleReportDBDao();
	}

	public static BattleReportDBDao getInstance() {
		return SingletonHolder.instance;
	}

	private ResultSetHandler<BattleReport> areport = new ResultSetHandler<BattleReport>() {

		@Override
		public BattleReport handle(ResultSet rs) throws SQLException {
			BattleReport battlereport = null;
			if (rs.next()) {
				battlereport = new BattleReport();
				battlereport.setId(rs.getLong("id"));
				try {
					InputStream is = rs.getBinaryStream("battleReport");
					if (is != null) {
						AllRound allround = ProtoMessageQzmj.AllRound.parseFrom(is);
						battlereport.setAllround(allround);
					}
				} catch (IOException e) {

				}
			}
			return battlereport;
		}

	};

	public boolean addBattleReport(BattleReport aattleReport) {
		boolean addRet = false;
		AllRound allround = aattleReport.getAllround();
		byte content1[] = new byte[0];
		if (allround != null) {
			content1 = allround.toByteArray();
		}
		QueryRunner runner = new QueryRunner(dataSource);
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
			MyBlob blob = new MyBlob(content1);
			int ret = runner.update(conn, "insert into realBattleReport(battleReport,roomtype,id)" + "values(?,?,?)", blob,
					aattleReport.getRoomtype(), aattleReport.getId());
			if (ret > 0) {
				addRet = true;
			}

		} catch (SQLException e) {
			logger.error("", e);
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return addRet;
	}
}
